<template>
  <div class="app-container">
    <div class="inner">
      <el-card class="box-card" v-show="isProject">
        <el-descriptions title="项目信息" :column="1" border>
          <el-descriptions-item label="项目名称">{{projectInfo.name}}</el-descriptions-item>
          <el-descriptions-item label="施工单位">{{projectInfo.constructionUnit}}</el-descriptions-item>
          <el-descriptions-item label="监理单位">{{projectInfo.supervisionUnit}}</el-descriptions-item>
          <el-descriptions-item label="项目简介">{{projectInfo.introduce}}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" style="margin-top: 20px;">
        <el-form-item label="文件名称" prop="roleName">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入文件名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="文件类型" prop="roleKey">
          <el-select v-model="queryParams.fileType" placeholder="请选择筛选条件">
            <el-option
              v-for="item in fileType"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="筛选条件" prop="roleKey" v-show="hasOptions">
          <el-select v-model="queryParams.secondDirectory" placeholder="请选择筛选条件">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="[`${this.permissions}`+':add']"
          >上传</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="[`${this.permissions}`+':batchDelete']"
          >批量删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <div class="fileTable">
        <el-table v-loading="loading" :data="fileList"
                  @selection-change="handleSelectionChange" style="font-size: 16px;!important;">
          <!--:header-cell-style="{background:'rgba(0,0,0,0.1)',color:'#606266'}"-->
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="文件名称" prop="name" :show-overflow-tooltip="true" width="240"/>
          <el-table-column label="文件类型" prop="fileType" :show-overflow-tooltip="true" width="150"/>
          <el-table-column label="属性" prop="secondDirectory" width="150" v-if="hasOptions" />
          <el-table-column label="上传时间" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleView(scope.row)"
                v-hasPermi="[`${permissions}`+':view']"
                :disabled="scope.row.fileType !== 'pdf' && scope.row.fileType !== 'tif' && scope.row.fileType !== 'jpg'
                && scope.row.fileType !== 'png' && scope.row.fileType !== 'jpeg'"
              >预览</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="handleDownload(scope.row)"
                v-hasPermi="[`${permissions}`+':download']"
              >下载</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="[`${permissions}`+':edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="[`${permissions}`+':rmv']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <pagination
        class="filePagination"
        v-show="total"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 上传文件对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="addForm" enctype="multipart/form-data" :rules="rules" label-width="100px">
          <el-form-item label="上传" prop="roleName">
            <el-upload
              class="upload-demo"
              action="#"
              :on-change="handleChange"
              :before-upload="handleBeforeUpload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              ref="upload"
              multiple
              :file-list="addForm.files"
              :http-request="uploadFile"
              :auto-upload="false">
              <el-button size="small" type="primary">点击选择文件</el-button>
            </el-upload>
            <div v-show="progressFlag" class="head-img">
              <el-progress :text-inside="true" :stroke-width="14" :percentage="progressPercent" status="success"></el-progress>
            </div>
          </el-form-item>
          <el-form-item label="属性" prop="roleName" v-show="hasOptions">
            <el-select v-model="addForm.secondDirectory" placeholder="请选择属性">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitAddForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="预览文件"
        :visible.sync="isViewPdf"
        append-to-body
        width="55vw"
      >
        <iframe :src="pdfUrl" frameborder="0" style="width: 52vw; height: 70vh"></iframe>
      </el-dialog>

      <el-dialog
        title="预览文件"
        :visible.sync="isViewImage"
        append-to-body
        width="55vw"
      >
        <img :src="imageUrl" style="width: 52vw;" alt="">
      </el-dialog>

      <!-- 分配角色数据权限对话框 -->
      <!-- 上传文件对话框 -->
      <el-dialog title="修改文件" :visible.sync="fileIsEdit" width="500px" append-to-body>
        <el-form ref="form" :model="editForm" enctype="multipart/form-data" :rules="rules" label-width="100px">
          <el-form-item label="上传" prop="roleName">
            <el-upload
              class="upload-demo"
              action="#"
              :on-change="handleEditChange"
              :before-upload="handleBeforeUpload"
              :on-preview="handlePreview"
              :on-remove="handleEditRemove"
              :before-remove="beforeRemove"
              ref="upload"
              :file-list="editForm.files"
              :http-request="uploadEditFile"
              :auto-upload="false">
              <el-button size="small" type="primary">点击选择文件</el-button>
            </el-upload>
            <div v-show="progressFlag" class="head-img">
              <el-progress :text-inside="true" :stroke-width="14" :percentage="progressPercent" status="success"></el-progress>
            </div>
          </el-form-item>
          <el-form-item label="属性" prop="roleName" v-show="hasOptions">
            <el-select v-model="editForm.secondDirectory" placeholder="请选择属性">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitEditForm">确 定</el-button>
          <el-button @click="fileIsEdit = false;">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import Tiff from "tiff.js"

import {
  getList,
  getSearchItem,
  searchForList,
  deleteFile,
  uploadFile,
  downloadFile,
  viewFile,
  editFile, geFileTypes
} from '@/api/devUnit/organization'

export default {
  name: "Role",
  dicts: ['sys_normal_disable'],
  data() {
    //定义上传文件校验规则
    let validateFileUrl = (rule, value, callback) =>{
      if(this.addForm.files.length < 1){
        callback(new Error("请上传文件"))
      }else{
        callback();
      }
    }
    return {
      //页面信息
      menu: '',
      name: '',
      projectId:'',
      permissions: '',
      projectInfo: {
        constructionUnit: "",
        id: 0,
        introduce: "",
        menu: "",
        menuName: "",
        name: "",
        supervisionUnit: ""
      },
      isProject: false,
      isViewPdf: false,
      isViewImage: false,
      pdfUrl: '',
      imageUrl: '',
      fileIsEdit: false,
      editId: -1,
      fileIsChange: false,
      editDic: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      fileNames : [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      fileList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        fileType: undefined,
        secondDirectory: undefined,
      },
      options: [],
      hasOptions: false,
      form: {

      },
      fileType: [
        {id: 'pdf', name: 'pdf'},
        {id: 'JPG', name: 'JPG'},
        {id: 'PNG', name: 'PNG'},
        {id: 'doc', name: 'doc'},
        {id: 'docx', name: 'docx'},
        {id: 'xlsx', name: 'xlsx'},
        {id: 'txt', name: 'txt'},
        {id: 'zip', name: 'zip'},
        {id: 'rar', name: 'rar'},
      ],
      fileData:'',
      // 表单参数
      addForm: {
        files: [],
        secondDirectory: '',
      },
      editForm: {
        files: [],
        secondDirectory: '',
      },
      // 表单校验
      rules: {
        //不知道能不能为空
        /*fileKey: [
          { required: true, message: "属性不能为空", trigger: "blur" }
        ],*/
        fileList: [
          { required: true, validator: validateFileUrl, trigger: "change" }
        ]
      },
      progressFlag: false,//进度条初始值隐藏
      progressPercent: 0//进度条初始值
    };
  },
  created() {
    const { params, query } = this.$route
    this.menu = query.menu;
    this.name = query.name;
    this.projectId = query.projectId;
    if(query.permissions != null){
      this.permissions = query.permissions
    }
    if(query.projectInfo != null){
      this.projectInfo = query.projectInfo
      this.isProject = true;
    }
    this.getList();
    this.getOptions();
    this.getFileTypes();
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      let htmlInfo = {'bucketName':this.menu,'firstDirectory':this.name,'sectionProjectId':this.projectId}
      getList(Object.assign(this.queryParams, htmlInfo)).then(response => {
          this.fileList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询筛选项列表 */
    getOptions() {
      let htmlInfo = {'menu':this.menu,'name':this.name}
      getSearchItem(htmlInfo).then(response => {
          this.options = response.data.itemList;
          if(this.options.length != 0){
            this.hasOptions = true;
          }
        }
      );
    },
    /** 查询文件类型列表 */
    getFileTypes() {
      let htmlInfo = {'menu':this.menu,'name':this.name}
      geFileTypes(htmlInfo).then(response => {
        this.fileType = response.data;
        console.log(this.fileType)
      });
    },
    /** 根据筛选项查询文件列表 */
    searchForList() {
      this.loading = true;
      let htmlInfo = {'bucketName':this.menu,'firstDirectory':this.name,'sectionProjectId':this.projectId}
      searchForList(Object.assign(this.queryParams, htmlInfo)).then(response => {
        this.fileList = response.rows;
        this.total = response.total;
        this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.addForm.secondDirectory = '';
      this.addForm.files = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.searchForList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        fileType: undefined,
        secondDirectory: undefined,
      };
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.fileNames = selection.map(item => item.name)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "上传文件";
      this.progressFlag = false;
      this.progressPercent = 0;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      let afile = new File([], row.name)
      this.editForm.files = [afile]
      this.editForm.secondDirectory = row.secondDirectory
      this.fileIsEdit = true;
      this.editId = row.id;
      this.editDic = row.secondDirectory;
      his.progressFlag = false;
      this.progressPercent = 0;
    },

    // 上传文件
    uploadFile(file) {
      this.fileData.append('files', file.file); // append增加数据
    },

    uploadEditFile(file) {
      this.fileData.append('file', file.file); // append增加数据
    },

    // 上传,提交表单
    submitAddForm() {
      //let fieldData = this.addForm;
      let that = this;
      if (this.addForm.files.secondDirectory === '') {
        this.$message({
          message: '请选择文件属性',
          type: 'warning'
        })
      } else if (this.addForm.files.length == 0) {
        this.$message({
          message: '请先选择文件',
          type: 'warning'
        })
      } else {
        this.fileData = new FormData(); // new formData对象

        this.$refs.upload.submit(); // 提交调用uploadFile函数
        this.fileData.append('bucketName',this.menu)
        this.fileData.append('firstDirectory',this.name)
        this.fileData.append('sectionProjectId',this.projectId)
        this.fileData.append('files',this.addForm.files)
        this.fileData.append('secondDirectory',this.addForm.secondDirectory)
        //修改progressFlag值
        that.progressFlag = true;
        let config = {
          onUploadProgress:progressEvent => {
            // progressEvent.loaded:已上传文件大小
            // progressEvent.total:被上传文件的总大小
            //进度条
            that.progressPercent = ((progressEvent.loaded / progressEvent.total) * 98) | 0;
          }
        }
        uploadFile(this.fileData, config).then(res => {
          if (res.code === 200 && res.data.length===0) {
            that.progressPercent = 100;
            this.$message({
              message: "上传成功",
              type: 'success'
            });
            this.fileList = [];
            this.getList();
            this.getFileTypes();
            this.open=false;
            that.progressFlag = false;
            that.progressPercent = 0;
          } else if(res.code === 200 && res.data.length!==0){
            that.progressPercent = 100;
            let msg=res.data[0];
            if(res.data.length>1){
              for(let i=1; i<res.data.length; i++){
                msg = msg +"、"+ res.data[i]
              }
            }
            this.$message({
              message: "文件:"+msg+"与已有文件同名，请修改后再上传",
              type: 'warning',
              duration:0,
              showClose:true,
            });
            this.fileList = [];
            this.getList();
            this.getFileTypes();
            this.open=false;
            that.progressPercent = 0;
            that.progressFlag = false;
          }

          else {
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        });

      }
    },
    submitEditForm(){
      if (this.editForm.files.secondDirectory === '') {
        this.$message({
          message: '请选择文件属性',
          type: 'warning'
        })
      } else if (this.editForm.files.length == 0) {
        this.$message({
          message: '请先选择文件',
          type: 'warning'
        })
      } else if(!this.fileIsChange && this.editDic == this.editForm.secondDirectory){
        this.$message({
          message: "请对文件进行修改",
          type: 'warning'
        });
      } else {
        this.fileData = new FormData(); // new formData对象


        this.$refs.upload.submit(); // 提交调用uploadFile函数

        this.fileData.append('bucketName',this.menu)
        this.fileData.append('firstDirectory',this.name)
        this.fileData.append('sectionProjectId',this.projectId)
        this.fileData.append('file',this.editForm.files[0])
        this.fileData.append('secondDirectory',this.editForm.secondDirectory)
        this.fileData.append('id',this.editId)

        if(!this.fileIsChange && this.editDic != this.editForm.secondDirectory){
          this.fileData.append('overwrite',true)
        }

        let that = this;
        //修改progressFlag值
        that.progressFlag = true;
        let config = {
          onUploadProgress:progressEvent => {
            // progressEvent.loaded:已上传文件大小
            // progressEvent.total:被上传文件的总大小
            //进度条
            that.progressPercent = ((progressEvent.loaded / progressEvent.total) * 98) | 0;
          }
        }

        editFile(this.fileData, config).then(res => {
          if (res.code === 200) {
            that.progressPercent = 100;
            that.progressFlag = false;
            that.progressPercent = 0;
            if(res.msg === "存在同名文件"){
              that.$modal.confirm(res.msg + '，是否确认修改文件名为"' + that.editForm.files[0].name + '"的数据项？').then(function() {

                that.progressFlag = true;
                that.fileData.append('overwrite',true)
                editFile(that.fileData, config).then(res => {
                  if (res.code === 200) {
                    that.progressPercent = 100;
                    that.progressFlag = false;
                    that.progressPercent = 0;
                    that.fileIsEdit = false;
                    that.$message({
                      message: "修改成功",
                      type: 'success'
                    });
                    that.fileList = [];
                    that.getList();
                    this.getFileTypes();

                  } else {
                    this.$message({
                      message: res.msg,
                      type: 'error'
                    })
                  }
                });
              })
            }else{
              this.$message({
                message: "修改成功",
                type: 'success'
              });
              this.fileList = [];
              this.getList();
              this.getFileTypes();
              this.fileIsEdit = false;
            }
          } else {
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        });

      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let fileIds = []
      let fileNames = []
      if (row.id == undefined){
        fileIds = this.ids
        fileNames = this.fileNames
      }else{
        fileIds = [row.id]
        fileNames = [row.name]
      }

      this.$modal.confirm('是否确认删除文件名为"' + fileNames + '"的数据项？').then(function() {
        return deleteFile(fileIds);
      }).then(() => {
        this.getList();
        this.getFileTypes();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleDownload(row) {
      let id = {'id': row.id}
      downloadFile(id).then(response => {
        window.location.href = response.msg
      });
    },
    handleView(row){
      let id = {'id': row.id}
      let that = this;
      viewFile(id).then(response => {
        if(row.fileType == "pdf"){
          that.isViewPdf = true;
          that.pdfUrl = response.msg
        }else{
          that.isViewImage = true;
          that.imageUrl = response.msg;
          if(row.fileType == "tif"){
            this.getTiffDataUrlHandler(that.imageUrl)
          }
        }
      });
    },
    // 获取tif图的dataUrl base64编码进行展示
    async getTiffDataUrlHandler (url) {
      const response = await fetch(url)
      const buffer = await response.arrayBuffer()
      const Tiff = require('tiff.js')
      const tiff = new Tiff({ buffer })
      this.imageUrl = tiff.toDataURL()
    },
    /** 文件上传相关 */
    handleBeforeUpload(file) {
      //const uploadLimit = 100
      //不确定会上传什么格式的文件
      //const uploadTypes = ['jpg', 'png', 'doc', 'docx', 'xlsx', 'txt', 'zip', 'rar', 'pdf']
      /*const filetype = file.name.replace(/.+\./, '')
      const isRightSize = (file.size || 0) / 1024 / 1024 < uploadLimit
      if (!isRightSize) {
        this.$message.error('文件大小超过 ' + uploadLimit + 'MB')
        return false
      }*/
      //不确定会上传什么格式的文件
      /*if (uploadTypes.indexOf(filetype.toLowerCase()) === -1) {
        this.$message.warning({
          message: '请上传后缀名为jpg、png、txt、pdf、doc、docx、xlsx、zip或rar的附件'
        })
        return false
      }*/

      return true
    },
    handleChange(file, fileList) {
      this.addForm.files=fileList
    },
    handleEditChange(file, fileList) {
      this.editForm.files = fileList.slice(-1);
      this.fileIsChange = true;
    },
    handleRemove(file, fileList) {
      this.addForm.files=fileList
    },
    handleEditRemove(file, fileList) {
      this.editForm.files=fileList
    },
    handlePreview(file) {
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    }
  }
};
</script>

<style scoped>
/*.app-container{
  min-height: calc(100vh - 84px);
  width: 100%;
  background: url("../../../assets/images/fileManageBackground.png");
  background-size: 100% 100%;
  padding: 0;
}

.inner{
  background: rgba(255,255,255,0.5);
  width: 100%;
  height: calc(100vh - 84px);
  padding: 20px;
}

.fileTable /deep/  .el-table, .el-table__expanded-cell {
  background-color: rgba(255,255,255,0.5);
}

.fileTable /deep/ .el-table tr {
  background-color: rgba(255,255,255,0.5)!important;
}
.fileTable /deep/  .el-table--enable-row-transition .el-table__body td, .el-table .cell{
  background-color: rgba(255,255,255,0.5);
}

.filePagination{
  background: rgba(255,255,255,0.5);
}*/
</style>
